package org.ehe.business.step.pdf;

import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.colors.Color;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.colors.DeviceRgb;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.borders.Border;
import com.itextpdf.layout.borders.SolidBorder;
import com.itextpdf.layout.element.*;
import com.itextpdf.layout.properties.*;
import lombok.extern.slf4j.Slf4j;
import org.ehe.business.step.domain.GeometryAnalysis;
import org.ehe.business.step.domain.ManufacturingEstimate;
import org.ehe.business.step.domain.STEPAnalysisResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * 增强修复版PDF文件生成器 - 解决字段标签和3D渲染问题
 */
@Slf4j
@Component
public class PDFGenerator {

    private static final String OUTPUT_DIR = "/Users/zhangenen/Downloads/pdf/";

    // 优化的配色方案
    private static final Color HEADER_BG = new DeviceRgb(41, 128, 185);     // 专业蓝色
    private static final Color SECTION_BG = new DeviceRgb(236, 240, 241);   // 浅灰色
    private static final Color ACCENT_COLOR = new DeviceRgb(52, 152, 219);  // 强调色
    private static final Color SUCCESS_COLOR = new DeviceRgb(39, 174, 96);  // 成功色
    private static final Color WARNING_COLOR = new DeviceRgb(241, 196, 15); // 警告色
    private static final Color ERROR_COLOR = new DeviceRgb(231, 76, 60);    // 错误色
    private static final Color TEXT_COLOR = new DeviceRgb(44, 62, 80);      // 文本色

    private static final NumberFormat CURRENCY_FORMAT = DecimalFormat.getCurrencyInstance();
    private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("#,##0.00");

    private PdfFont boldFont;
    private PdfFont regularFont;

    @Autowired
    private Render3DModelPreview render3DModelPreview;

    public String generatePDFReport(STEPAnalysisResult result, String originalFileName) throws IOException {
        File outputDir = new File(OUTPUT_DIR);
        if (!outputDir.exists()) {
            outputDir.mkdirs();
        }

        String pdfFileName = originalFileName.replaceAll("\\.[^.]+$", "") + "_analysis_report.pdf";
        String pdfPath = OUTPUT_DIR + pdfFileName;

        try (PdfWriter writer = new PdfWriter(pdfPath);
             PdfDocument pdf = new PdfDocument(writer)) {

            // 初始化字体
            initializeFonts();

            // 创建文档
            Document document = new Document(pdf, PageSize.A4);
            document.setMargins(40, 40, 40, 40);

            // 添加标题页眉
            addHeader(document, result);

            // 添加3D模型预览
            addModelPreview(document, result, originalFileName);

            // 添加主要内容
            addMainContent(document, result);

            // 添加页脚
            addFooter(document, result);

            log.info("增强PDF报告生成成功: {}", pdfPath);
        } catch (Exception e) {
            log.error("生成PDF报告失败", e);
            throw e;
        }

        return pdfPath;
    }

    /**
     * 修复字体初始化问题
     */
    private void initializeFonts() {
        try {
            boldFont = PdfFontFactory.createFont("font/SIMHEI.TTF", "Identity-H", PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED);
            regularFont = PdfFontFactory.createFont("font/STZHONGS.TTF", "Identity-H", PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED);
            log.debug("字体初始化成功");
        } catch (IOException e) {
            log.error("字体初始化失败", e);
            throw new RuntimeException("无法初始化PDF字体", e);
        }
    }

    private void addHeader(Document document, STEPAnalysisResult result) {
        // 创建标题区域
        Table headerTable = new Table(UnitValue.createPercentArray(new float[]{1, 2, 1}));
        headerTable.setWidth(UnitValue.createPercentValue(100));
        headerTable.setMarginBottom(30);

        // 左侧：公司Logo占位
        Cell logoCell = new Cell()
            .add(new Paragraph("怡和机械")
                .setFont(boldFont)
                .setFontSize(14)
                .setFontColor(HEADER_BG))
            .setBorder(Border.NO_BORDER)
            .setPadding(10);
        headerTable.addCell(logoCell);

        // 中间：主标题
        Cell titleCell = new Cell()
            .add(new Paragraph("分析报告")
                .setFont(boldFont)
                .setFontSize(28)
                .setTextAlignment(TextAlignment.CENTER)
                .setFontColor(HEADER_BG))
            .add(new Paragraph("3D Model Analysis Report")
                .setFont(regularFont)
                .setFontSize(14)
                .setItalic()
                .setTextAlignment(TextAlignment.CENTER)
                .setFontColor(TEXT_COLOR)
                .setMarginTop(5))
            .setBorder(Border.NO_BORDER)
            .setVerticalAlignment(VerticalAlignment.MIDDLE);
        headerTable.addCell(titleCell);

        // 右侧：日期和状态
        String analysisDate = result.getAnalysisTime() != null ?
            result.getAnalysisTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) :
            "未知日期";

        Cell statusCell = new Cell()
            .add(new Paragraph("生成日期")
                .setFont(regularFont)
                .setFontSize(10)
                .setFontColor(TEXT_COLOR))
            .add(new Paragraph(analysisDate)
                .setFont(boldFont)
                .setFontSize(12)
                .setFontColor(HEADER_BG))
            .add(new Paragraph("\n状态: 已完成")
                .setFont(boldFont)
                .setFontSize(10)
                .setFontColor(SUCCESS_COLOR))
            .setBorder(Border.NO_BORDER)
            .setTextAlignment(TextAlignment.RIGHT)
            .setPadding(10);
        headerTable.addCell(statusCell);

        document.add(headerTable);

        // 添加分割线
        document.add(new Paragraph()
            .setBorderBottom(new SolidBorder(HEADER_BG, 2))
            .setMarginBottom(20));
    }

    private void addModelPreview(Document document, STEPAnalysisResult result, String originalFileName) {
        // 创建3D预览区域
        Div previewSection = new Div();
        previewSection.setBackgroundColor(new DeviceRgb(248, 249, 250));
        previewSection.setPadding(20);
        previewSection.setMarginBottom(30);
        previewSection.setBorder(new SolidBorder(new DeviceRgb(220, 220, 220), 1));

        Paragraph previewTitle = new Paragraph("3D模型预览")
            .setFont(boldFont)
            .setFontSize(18)
            .setFontColor(HEADER_BG)
            .setMarginBottom(15);
        previewSection.add(previewTitle);

        // 尝试生成3D预览
        String previewImagePath = generateModelPreview(result, originalFileName);

        if (previewImagePath != null && new File(previewImagePath).exists()) {
            try {
                ImageData imageData = ImageDataFactory.create(previewImagePath);
                Image image = new Image(imageData)
                    .setHorizontalAlignment(HorizontalAlignment.CENTER)
                    .setAutoScale(true)
                    .setMaxWidth(400)
                    .setMaxHeight(300);

                image.setBorder(new SolidBorder(new DeviceRgb(200, 200, 200), 1));
                previewSection.add(image);

                previewSection.add(new Paragraph("图1: STEP文件3D渲染视图")
                    .setFont(regularFont)
                    .setFontSize(12)
                    .setItalic()
                    .setTextAlignment(TextAlignment.CENTER)
                    .setFontColor(TEXT_COLOR)
                    .setMarginTop(10));

            } catch (Exception e) {
                log.warn("无法加载3D预览图: {}", e.getMessage());
                previewSection.add(createWarningBox("3D预览图加载失败: " + e.getMessage()));
            }
        } else {
            previewSection.add(createWarningBox("3D预览不可用 - FreeCAD服务暂时不可用"));
        }

        document.add(previewSection);
    }

    /**
     * 生成3D模型预览
     */
    private String generateModelPreview(STEPAnalysisResult result, String originalFileName) {
        try {
            // 如果结果中已有预览路径，先尝试使用
            if (result.getModelPreviewPath() != null) {
                File existingPreview = new File(result.getModelPreviewPath());
                if (existingPreview.exists() && existingPreview.length() > 1000) {
                    return result.getModelPreviewPath();
                }
            }

            // 尝试重新生成预览
            if (render3DModelPreview != null) {
                // 假设原始STEP文件在某个目录下
                String stepFilePath = "/path/to/step/files/" + originalFileName; // 需要根据实际情况调整
                File stepFile = new File(stepFilePath);

                if (stepFile.exists()) {
                    return render3DModelPreview.modelPreview(stepFile);
                } else {
                    log.warn("STEP文件不存在: {}", stepFilePath);
                }
            }

            return null;
        } catch (Exception e) {
            log.error("生成3D预览时出错", e);
            return null;
        }
    }

    private void addMainContent(Document document, STEPAnalysisResult result) {
        // 创建两列布局
        Table mainTable = new Table(UnitValue.createPercentArray(new float[]{1}));
        mainTable.setWidth(UnitValue.createPercentValue(100));
        mainTable.setMarginTop(20);

        // 左列
        Cell leftCell = new Cell().setBorder(Border.NO_BORDER).setPadding(10);
        leftCell.add(createEnhancedSection("📋 基础信息", createEnhancedInfoTable(result)));
        leftCell.add(createEnhancedSection("🔬 材料分析", createMaterialAnalysis(result)));
        leftCell.add(createEnhancedSection("✅ 质量评估", createQualityAssessment(result)));
        //mainTable.addCell(leftCell);

        // 右列
        //Cell rightCell = new Cell().setBorder(Border.NO_BORDER).setPadding(10);
        leftCell.add(createEnhancedSection("📐 几何分析", createGeometryAnalysisTable(result.getGeometryAnalysis())));
        leftCell.add(createEnhancedSection("⚙️ 制造估算", createManufacturingEstimateTable(result.getManufacturingEstimate())));
        mainTable.addCell(leftCell);

        document.add(mainTable);
    }

    private Div createEnhancedSection(String title, IBlockElement content) {
        Div section = new Div();
        section.setMarginBottom(25);

        // 创建美观的标题
        Paragraph titlePara = new Paragraph(title)
            .setFont(boldFont)
            .setFontSize(16)
            .setBackgroundColor(HEADER_BG)
            .setFontColor(ColorConstants.WHITE)
            .setPadding(12)
            .setMarginBottom(0);

        // 内容容器
        Div contentDiv = new Div();
        contentDiv.setBackgroundColor(ColorConstants.WHITE);
        contentDiv.setBorder(new SolidBorder(HEADER_BG, 1));
        contentDiv.setPadding(15);
        contentDiv.add(content);

        section.add(titlePara);
        section.add(contentDiv);

        return section;
    }

    /**
     * 修复基础信息表格 - 确保字段名称正确显示
     */
    private Table createEnhancedInfoTable(STEPAnalysisResult result) {
        Table table = new Table(UnitValue.createPercentArray(new float[]{1, 2}));
        table.setWidth(UnitValue.createPercentValue(100));

        // 添加表格行，确保字段名和值都正确显示
        addEnhancedTableRow(table, "文件名称",
            result.getFileName() != null ? result.getFileName() : "未知文件", null);

        addEnhancedTableRow(table, "文件大小",
            formatFileSize(result.getFileSize()), null);

        addEnhancedTableRow(table, "版本",
            result.getStepVersion() != null ? result.getStepVersion() : "未知版本", null);

        addEnhancedTableRow(table, "CAD软件",
            result.getCadSoftware() != null ? result.getCadSoftware() : "未知软件", null);

        addEnhancedTableRow(table, "单位",
            result.getUnit() != null ? result.getUnit() : "未知单位", null);

        // 复杂度用颜色标识
        String complexity = result.getComplexity() != null ? result.getComplexity() : "未知";
        Color complexityColor = getComplexityColor(complexity);
        addEnhancedTableRow(table, "模型复杂度", complexity, complexityColor);

        addEnhancedTableRow(table, "分析耗时",
            result.getProcessingTimeMs() + "ms", null);

        return table;
    }

    /**
     * 修复表格行添加方法 - 确保显示完整的标签和值
     */
    private void addEnhancedTableRow(Table table, String header, String value, Color valueColor) {
        if (header == null) header = "未知字段";
        if (value == null) value = "N/A";

        // 标题单元格
        Cell headerCell = new Cell()
            .add(new Paragraph(header)
                .setFont(boldFont)
                .setFontSize(11)
                .setFontColor(TEXT_COLOR))
            .setBackgroundColor(SECTION_BG)
            .setPadding(8)
            .setBorder(new SolidBorder(new DeviceRgb(220, 220, 220), 0.5f))
            .setVerticalAlignment(VerticalAlignment.MIDDLE);

        // 值单元格
        Paragraph valuePara = new Paragraph(value)
            .setFont(regularFont)
            .setFontSize(11)
            .setFontColor(valueColor != null ? valueColor : TEXT_COLOR);

        if (valueColor != null) {
            valuePara.setFont(boldFont);
        }

        Cell valueCell = new Cell()
            .add(valuePara)
            .setPadding(8)
            .setBorder(new SolidBorder(new DeviceRgb(220, 220, 220), 0.5f))
            .setVerticalAlignment(VerticalAlignment.MIDDLE);

        table.addCell(headerCell);
        table.addCell(valueCell);
    }

    private Div createMaterialAnalysis(STEPAnalysisResult result) {
        Div materialDiv = new Div();

        if (result.getMaterials() != null && !result.getMaterials().isEmpty()) {
            for (String material : result.getMaterials()) {
                Div materialItem = new Div();
                materialItem.setBackgroundColor(new DeviceRgb(240, 248, 255));
                materialItem.setPadding(10);
                materialItem.setMarginBottom(8);
                materialItem.setBorder(new SolidBorder(ACCENT_COLOR, 1));

                materialItem.add(new Paragraph("🔹 " + material)
                    .setFont(regularFont)
                    .setFontSize(12)
                    .setMarginBottom(0));

                materialDiv.add(materialItem);
            }
        } else {
            materialDiv.add(createInfoBox("未指定材料信息"));
        }

        return materialDiv;
    }

    /**
     * 修复几何分析表格
     */
    private Table createGeometryAnalysisTable(GeometryAnalysis analysis) {
        Table table = new Table(UnitValue.createPercentArray(new float[]{1, 1}));
        table.setWidth(UnitValue.createPercentValue(100));

        if (analysis != null) {
            addEnhancedTableRow(table, "边界尺寸",
                analysis.getDimensions() != null ? analysis.getDimensions() : "未知", null);

            addEnhancedTableRow(table, "估算体积",
                formatVolume(analysis.getEstimatedVolume()) + " " +
                    (analysis.getVolumeUnit() != null ? analysis.getVolumeUnit() : "mm³"),
                ACCENT_COLOR);

            addEnhancedTableRow(table, "表面复杂度",
                analysis.getSurfaceComplexityScore() + " 分",
                getComplexityScoreColor(analysis.getSurfaceComplexityScore()));

            // 表面类型统计
            if (analysis.getSurfaceTypes() != null && !analysis.getSurfaceTypes().isEmpty()) {
                Cell surfaceHeader = new Cell(1, 2)
                    .add(new Paragraph("表面类型分布")
                        .setFont(boldFont)
                        .setFontSize(12)
                        .setFontColor(ColorConstants.WHITE))
                    .setBackgroundColor(ACCENT_COLOR)
                    .setPadding(8);
                table.addCell(surfaceHeader);

                for (Map.Entry<String, Integer> entry : analysis.getSurfaceTypes().entrySet()) {
                    addEnhancedTableRow(table,
                        getSurfaceTypeDisplayName(entry.getKey()),
                        entry.getValue() + " 个",
                        null);
                }
            }
        } else {
            addEnhancedTableRow(table, "几何分析", "数据不可用", WARNING_COLOR);
        }
        return table;
    }

    /**
     * 修复制造估算表格
     */
    private Table createManufacturingEstimateTable(ManufacturingEstimate estimate) {
        Table table = new Table(UnitValue.createPercentArray(new float[]{1, 1}));
        table.setWidth(UnitValue.createPercentValue(100));

        if (estimate != null) {
            addEnhancedTableRow(table, "预估工期", estimate.getEstimatedDays() + " 天", SUCCESS_COLOR);
            addEnhancedTableRow(table, "加工时间", estimate.getMachiningHours() + " 小时", null);
            addEnhancedTableRow(table, "材料利用率",
                DECIMAL_FORMAT.format(estimate.getMaterialUtilization()) + "%",
                getUtilizationColor(estimate.getMaterialUtilization()));
            addEnhancedTableRow(table, "加工难度",
                estimate.getDifficultyLevel() + " (" + estimate.getDifficultyScore() + ")",
                getDifficultyColor(estimate.getDifficultyLevel()));
            addEnhancedTableRow(table, "预估成本",
                formatCurrency(estimate.getEstimatedCost()),
                ERROR_COLOR);

            // 成本明细
            if (estimate.getCostBreakdown() != null && !estimate.getCostBreakdown().isEmpty()) {
                Cell costHeader = new Cell(1, 2)
                    .add(new Paragraph("成本明细分解")
                        .setFont(boldFont)
                        .setFontSize(12)
                        .setFontColor(ColorConstants.WHITE))
                    .setBackgroundColor(new DeviceRgb(155, 89, 182))
                    .setPadding(8);
                table.addCell(costHeader);

                for (Map.Entry<String, Double> entry : estimate.getCostBreakdown().entrySet()) {
                    addEnhancedTableRow(table, entry.getKey(), formatCurrency(entry.getValue()), null);
                }
            }
        } else {
            addEnhancedTableRow(table, "制造估算", "数据不可用", WARNING_COLOR);
        }
        return table;
    }

    private Div createQualityAssessment(STEPAnalysisResult result) {
        Div qualityDiv = new Div();

        // 质量评分
        int qualityScore = result.getQualityScore();
        Color scoreColor = getQualityScoreColor(qualityScore);

        Div scoreDiv = new Div();
        scoreDiv.setBackgroundColor(scoreColor);
        scoreDiv.setFontColor(ColorConstants.WHITE);
        scoreDiv.setPadding(15);
        scoreDiv.setMarginBottom(15);

        scoreDiv.add(new Paragraph("质量评分: " + qualityScore + "/100")
            .setFont(boldFont)
            .setFontSize(16)
            .setTextAlignment(TextAlignment.CENTER)
            .setMarginBottom(0));

        qualityDiv.add(scoreDiv);

        // 质量问题
        if (result.getQualityIssues() != null && !result.getQualityIssues().isEmpty()) {
            qualityDiv.add(new Paragraph("⚠️ 发现的问题:")
                .setFont(boldFont)
                .setFontColor(WARNING_COLOR)
                .setMarginBottom(8));

            for (String issue : result.getQualityIssues()) {
                qualityDiv.add(createWarningItem(issue));
            }
        } else {
            qualityDiv.add(createSuccessItem("未发现质量问题"));
        }

        // 改进建议
        if (result.getRecommendations() != null && !result.getRecommendations().isEmpty()) {
            qualityDiv.add(new Paragraph("💡 改进建议:")
                .setFont(boldFont)
                .setFontColor(SUCCESS_COLOR)
                .setMarginTop(15)
                .setMarginBottom(8));

            for (String rec : result.getRecommendations()) {
                qualityDiv.add(createSuccessItem(rec));
            }
        }

        return qualityDiv;
    }

    private void addFooter(Document document, STEPAnalysisResult result) {
        document.add(new Paragraph()
            .setBorderTop(new SolidBorder(HEADER_BG, 1))
            .setMarginTop(30)
            .setMarginBottom(20));

        Table footerTable = new Table(UnitValue.createPercentArray(new float[]{1, 1, 1}));
        footerTable.setWidth(UnitValue.createPercentValue(100));

        String requestId = result.getRequestId() != null ? result.getRequestId() : "N/A";
        String analysisTime = result.getAnalysisTime() != null ?
            result.getAnalysisTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) :
            "未知时间";

        Cell leftFooter = new Cell()
            .add(new Paragraph("报告ID: " + requestId)
                .setFont(regularFont)
                .setFontSize(9)
                .setFontColor(TEXT_COLOR))
            .setBorder(Border.NO_BORDER);

        Cell centerFooter = new Cell()
            .add(new Paragraph("生成时间: " + analysisTime)
                .setFont(regularFont)
                .setFontSize(9)
                .setTextAlignment(TextAlignment.CENTER)
                .setFontColor(TEXT_COLOR))
            .setBorder(Border.NO_BORDER);

        Cell rightFooter = new Cell()
            .add(new Paragraph("Powered by STEP Analyzer v1.0")
                .setFont(regularFont)
                .setFontSize(9)
                .setTextAlignment(TextAlignment.RIGHT)
                .setFontColor(TEXT_COLOR))
            .setBorder(Border.NO_BORDER);

        footerTable.addCell(leftFooter);
        footerTable.addCell(centerFooter);
        footerTable.addCell(rightFooter);

        document.add(footerTable);
    }

    // 辅助方法
    private Div createWarningBox(String message) {
        Div warningBox = new Div();
        warningBox.setBackgroundColor(new DeviceRgb(255, 243, 205));
        warningBox.setBorder(new SolidBorder(WARNING_COLOR, 1));
        warningBox.setPadding(15);
        warningBox.add(new Paragraph("⚠️ " + message)
            .setFont(regularFont)
            .setFontSize(12)
            .setFontColor(new DeviceRgb(138, 109, 59))
            .setMarginBottom(0));
        return warningBox;
    }

    private Div createInfoBox(String message) {
        Div infoBox = new Div();
        infoBox.setBackgroundColor(new DeviceRgb(217, 237, 247));
        infoBox.setBorder(new SolidBorder(ACCENT_COLOR, 1));
        infoBox.setPadding(15);
        infoBox.add(new Paragraph("ℹ️ " + message)
            .setFont(regularFont)
            .setFontSize(12)
            .setFontColor(new DeviceRgb(49, 112, 143))
            .setMarginBottom(0));
        return infoBox;
    }

    private Div createWarningItem(String text) {
        Div item = new Div();
        item.setBackgroundColor(new DeviceRgb(255, 245, 245));
        item.setBorder(new SolidBorder(ERROR_COLOR, 1));
        item.setPadding(8);
        item.setMarginBottom(5);
        item.add(new Paragraph("• " + text)
            .setFont(regularFont)
            .setFontSize(11)
            .setFontColor(ERROR_COLOR)
            .setMarginBottom(0));
        return item;
    }

    private Div createSuccessItem(String text) {
        Div item = new Div();
        item.setBackgroundColor(new DeviceRgb(245, 255, 245));
        item.setBorder(new SolidBorder(SUCCESS_COLOR, 1));
        item.setPadding(8);
        item.setMarginBottom(5);
        item.add(new Paragraph("• " + text)
            .setFont(regularFont)
            .setFontSize(11)
            .setFontColor(SUCCESS_COLOR)
            .setMarginBottom(0));
        return item;
    }

    // 颜色辅助方法
    private Color getComplexityColor(String complexity) {
        if (complexity == null) return TEXT_COLOR;
        switch (complexity) {
            case "简单": return SUCCESS_COLOR;
            case "中等": return WARNING_COLOR;
            case "复杂": return ERROR_COLOR;
            default: return TEXT_COLOR;
        }
    }

    private Color getComplexityScoreColor(int score) {
        if (score < 100) return SUCCESS_COLOR;
        else if (score < 300) return WARNING_COLOR;
        else return ERROR_COLOR;
    }

    private Color getUtilizationColor(double utilization) {
        if (utilization > 80) return SUCCESS_COLOR;
        else if (utilization > 60) return WARNING_COLOR;
        else return ERROR_COLOR;
    }

    private Color getDifficultyColor(String difficulty) {
        if (difficulty == null) return TEXT_COLOR;
        switch (difficulty) {
            case "简单": return SUCCESS_COLOR;
            case "中等": return WARNING_COLOR;
            case "困难": return ERROR_COLOR;
            default: return TEXT_COLOR;
        }
    }

    private Color getQualityScoreColor(int score) {
        if (score >= 80) return SUCCESS_COLOR;
        else if (score >= 60) return WARNING_COLOR;
        else return ERROR_COLOR;
    }

    private String getSurfaceTypeDisplayName(String surfaceType) {
        if (surfaceType == null) return "未知";
        switch (surfaceType.toUpperCase()) {
            case "PLANE": return "平面";
            case "CYLINDRICAL_SURFACE": return "圆柱面";
            case "SPHERICAL_SURFACE": return "球面";
            case "CONICAL_SURFACE": return "圆锥面";
            case "TOROIDAL_SURFACE": return "环面";
            case "B_SPLINE_SURFACE": return "B样条面";
            default: return surfaceType;
        }
    }

    // 格式化方法
    private String formatFileSize(long bytes) {
        if (bytes <= 0) return "0 B";
        if (bytes < 1024) return bytes + " B";
        if (bytes < 1024 * 1024) return DECIMAL_FORMAT.format(bytes / 1024.0) + " KB";
        return DECIMAL_FORMAT.format(bytes / (1024.0 * 1024.0)) + " MB";
    }

    private String formatCurrency(double amount) {
        return "¥" + DECIMAL_FORMAT.format(amount);
    }

    private String formatVolume(double volume) {
        if (volume <= 0) return "0.00";
        return DECIMAL_FORMAT.format(volume);
    }
}
